package com.ecomm.util;

import java.io.File;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;


public class Function {
    /**
     * 将一个字符串转为合法的sql语句要求的表示方法。主要是对单引号的处理
     *
     * @param str
     * @return 处理后的字符串
     */
    public static String formatSQLString(String str) {
        if (str == null)
            return null;
        StringBuffer buf = new StringBuffer(str);

        int i = 0;
        for (int n = buf.length(); i < n; i++)
            if (buf.charAt(i) == '\'') {
                buf.replace(i, i + 1, "''");
                n++;
                i++;
            }
        return buf.toString();
    }

    /**
     * 创建一个定长的字符串，不足的部分用指定的字符补齐
     */
    public static String formatString(String a, int length, char b) {
        if (a == null) {
            return "";
        }

        if (a.length() > length) {
            return a.substring(0, length);
        }
        if (a.length() == length) {
            return a;
        }
        StringBuffer buf = new StringBuffer(length);
        buf.append(a);
        for (int i = 0; i < length - a.length(); i++) {
            buf.append(b);
        }
        return buf.toString();
    }

    /**
     * 创建一个定长的字符串，多余的部分用指定的字符代替
     */
    public static String formatStringElide(String a, int length, String b) {
        String sBack = "";
        if (a != null) {
            if (a.length() > length) {
                sBack = a.substring(0, length) + b;
            } else {
                sBack = a;
            }
        }
        return sBack;

    }

    /**
     * 此方法将返回一个定长的，在源串前补“a”的字符串
     *
     * @param sourceString 源串
     * @param nlength      要返回字符串的长度
     * @param a            要在源串前加补的字符
     * @return 返回一个前补a的定长字符串
     */
    public static String preFormatString(String sourceString, int nlength, String a) {
        String sZero = "";
        if (sourceString != null) {
            for (int i = 0; i < nlength - sourceString.length(); i++) {
                sZero += a;
            }
            sZero += sourceString;
        }
        return sZero;
    }


    /**
     * 取得数据库的日期类型的字符串表示方法
     *
     * @param dt
     * @return
     */
    public static String getSQLDateStringFormat(String dbtype, java.util.Date dt) {
        return "";
    }

    public static String getSQLDateStringFormat(String dbtype, java.sql.Date dt) {
        return "";
    }

    public static String getSQLDateStringFormat(String dbtype, java.sql.Timestamp dt) {
        return "";
    }

    /**
     * 取得指定数据库的取字符串长度函数的名称
     *
     * @param dbtype    数据库类型
     * @param fieldname 字段名
     * @return
     */
    public static String getSQLStringLengthFormat(String dbtype, String fieldname) {
        if ("oracle".equalsIgnoreCase(dbtype)) {
            return "length(" + fieldname + ")";
        }
        if ("mssql".equalsIgnoreCase(dbtype)) {
            return "len(" + fieldname + ")";
        }
        return "length(" + fieldname + ")";
    }

    /**
     * 返回指定字段的null 和 "" 的条件语句
     *
     * @param dbtype    数据库类型
     * @param fieldname 字段名
     * @return 返回 条件字符串,如 id is null
     */
    public static String getFieldNullSQL(String dbtype, String fieldname) {
        if (DBType.ORACLE.equals(dbtype)) {
            return fieldname + " is null ";
        } else if (DBType.MSSQL.equals(dbtype)) {
            return fieldname + " is null or " + fieldname + "='' ";
	    } else if (DBType.MYSQL.equals(dbtype)) {
	        return fieldname + " is null or " + fieldname + "='' ";
	    } else if (DBType.SYBASE.equals(dbtype)) {
	        return fieldname + " is null or " + fieldname + "='' ";
	    }
        return "";
    }

    /**
     * 返回指定字段的 不满足 null 和 "" 的条件语句
     *
     * @param dbtype    数据库类型
     * @param fieldname 字段名
     * @return 返回 条件字符串,如 id is not null
     */
    public static String getFieldNotNullSQL(String dbtype, String fieldname) {
        if (DBType.ORACLE.equals(dbtype)) {
            return fieldname + " is not null ";
        } else if (DBType.MSSQL.equals(dbtype)) {
            return fieldname + " is not null and " + fieldname + "<>'' ";
        } else if (DBType.MYSQL.equals(dbtype)) {
            return fieldname + " is not null and " + fieldname + "<>'' ";
        }else if (DBType.SYBASE.equals(dbtype)) {
            return fieldname + " is not null and " + fieldname + "<>'' ";
        }else{
        	return fieldname + " is not null ";
        }
    }

    /**
     * 取得数据库的系统时间函数的字符串表示方法
     *
     * @return
     */
    public static String getDBSystemTimeFormat(String dbtype) {
        return "";
    }

    /**
     * 取得指定文件名的mimetype类型
     *
     * @param filename
     * @return
     */
    public static String getMimetype(String filename) {
        final String STREAM_TYPE = "application/octet-stream";
        String fileName = normalizeString(filename);
        String ext = null;
        String sRet = null;
        if (!filename.equals("")) {
            int i = filename.lastIndexOf('.');
            if (i == -1) {
                sRet = STREAM_TYPE;
            } else {
                ext = fileName.substring(i + 1, fileName.length());
                sRet = MimeType.getMimeType(ext);
                if (sRet == null) {
                    sRet = STREAM_TYPE;
                }
            }
        }
        return sRet;
    }

    public static String normalizeString(String strValue) {
        return ((strValue == null) ? "" : strValue.trim());
    }

    /**
     * 将当前日期转换为指定格式的字符串
     *
     * @param pattern 格式
     * @return String
     */
    public static String getDateStringByPattern(String pattern) {
        Date date = new Date();
        return getDateStringByPattern(date, pattern);
    }

    /**
     * 将指定日期转换为指定格式的字符串
     *
     * @param date    ( java.util.Date )
     * @param pattern 日期格式，如："yyyy-MM-dd" ，"yyyy-MM-dd HH:mm:ss"，"HH:mm:ss"
     * @return String
     */
    public static String getDateStringByPattern(Date date, String pattern) {
        SimpleDateFormat sf = new SimpleDateFormat(pattern);
        String str = sf.format(date);
        return str;
    }

    /**
     * 必须是符合Timestamp的格式的
     *
     * @param strts
     * @param pattern
     * @return
     */
    public static String getTimestampStringByPattern(String strts, String pattern) {
        Timestamp ts = Timestamp.valueOf(strts);
        return getDateStringByPattern(ts, pattern);
    }

    /**
     * 将指定日期转换为指定格式的字符串
     *
     * @param ts      ( java.util.Timestamp )
     * @param pattern 日期格式，如："yyyy-MM-dd" ，"yyyy-MM-dd HH:mm:ss"，"HH:mm:ss"
     * @return String
     */
    public static String getDateStringByPattern(Timestamp ts, String pattern) {
        SimpleDateFormat sf = new SimpleDateFormat(pattern);
        String str = sf.format(ts);
        return str;
    }

    /**
     * 取得给定时间的字符串表示
     *
     * @param ts java.sql.Timestamp
     * @return String 格式 如2003-03-03 19:01:00
     */
    public static String getDateTimeString(java.sql.Timestamp ts) {
        if (ts == null) return "";
        String str = ts.toString();
        if (str.length() >= 19) {
            str = str.substring(0, 19);
        }
        return str;
    }

    /**
     * 取得系统当前的时间，以Timestamp 表示
     *
     * @ return 返回Timestamp对象
     */
    public static Timestamp getDateTime() {
        java.util.Date date = new java.util.Date();
        return (new java.sql.Timestamp(date.getTime()));
    }

    /**
     * 取得当前系统时间的字符串表示
     *
     * @return String 格式 如2003-03-03 19:01:00
     */
    public static String getDateTimeString() {
        java.sql.Timestamp ts = getDateTime();
        return getDateTimeString(ts);
    }

    /**
     * construct a Date through a string like "yyyy-mm-dd"
     *
     * @param time
     * @return
     * @throws java.sql.SQLException
     */
    public static java.sql.Date getDate(String time) throws SQLException {
//    Timestamp ts = getDateTime(time);
//    return new java.sql.Date(ts.getTime());
        return java.sql.Date.valueOf(time);
    }

    /**
     * 返回一个当前日期的字符串 格式为“YYYY-MM-DD”
     *
     * @return
     */
    public static String getDateString() {
        java.sql.Timestamp ts = getDateTime();
        String str = getDateTimeString(ts);
        if (str.length() >= 10) {
            str = str.substring(0, 10);
        }
        return str;

    }


    /**
     * construct a timestamp through a string like "yyyy-mm-dd" or "yyyy-mm-dd hh:mm:ss"
     *
     * @param sDt
     * @return
     */
    static public java.sql.Timestamp getDateTime(String sDt) {
        if (sDt == null || "".equals(sDt.trim()))
            return null;
        try {
            //sDt format:yyyy-mm-dd hh:mm:ss.fffffffff
            return java.sql.Timestamp.valueOf(sDt);
        } catch (IllegalArgumentException iae) {
            sDt = sDt + " 00:00:00";
            return java.sql.Timestamp.valueOf(sDt);
        }
    }

    public static String toChinese(String s) {
        String sRet = null;

        //如果不需要解码
        if (!Config.getBoolean("encoding", true)) {
            return s==null?"":s;
        }
        if (s == null) {
            sRet = "";
        } else {
            try {
                sRet = new String(s.getBytes("8859_1"), "GBK");
            } catch (Exception e) {
                Logger.getLog("com.ecomm.util.function").error("解码出现异常。", e);
                sRet = "??";
            }
        }
        return sRet;
    }


    /**
     * 给一个url追加参数和参数值。
     *
     * @param url
     * @param parameter
     * @param value
     * @return
     */
    public static String URLAppendParameter(String url, String parameter, String value) {
        StringBuffer sRet = new StringBuffer();
        if (url != null) {
            sRet.append(url);
            if (url.indexOf("?") > -1)   //已经有参数
            {
                sRet.append("&");
            } else {
                sRet.append("?");
            }
            sRet.append(parameter);
            sRet.append("=");
            sRet.append(value);
        }
        return sRet.toString();

    }


    /**
     * 返回格式化的路径 ，形如： 2003 / 07 /
     *
     * @param sPath
     * @return
     */
    public static String formatPath(String sPath) {
        if (sPath == null || "".equals(Function.normalizeString(sPath))) {
            return "";
        }

        if (sPath.charAt(0) == '/') {
            sPath = sPath.substring(1, sPath.length());
        }

        if (sPath.charAt(sPath.length() - 1) != '/') {
            sPath = sPath + "/";
        }
        return sPath;
    }

    /**
     * parse date from string with specific format.
     * @param strDate a date string
     * @param nFmtDate specific date string format defined in this class.
     * @exception raise ParseException, if string format dismathed.
     * @return Date,
     */

    /**
     * the following const is to define date format.
     */
    public static final int FMT_DATE_YYYYMMDD = 1;
    public static final int FMT_DATE_YYYYMMDD_HHMMSS = 2;
    public static final int FMT_DATE_HHMMSS = 3;
    public static final int FMT_DATE_HHMM = 4;


    public static java.util.Date parseDate(String strDate, int nFmtDate) throws Exception {

        java.text.SimpleDateFormat fmtDate = null;
        java.text.ParsePosition pos = new java.text.ParsePosition(0);
        switch (nFmtDate) {
            default:
            case FMT_DATE_YYYYMMDD:
                fmtDate = new java.text.SimpleDateFormat("yyyy-MM-dd");
                break;
            case FMT_DATE_YYYYMMDD_HHMMSS:
                fmtDate = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                break;
            case FMT_DATE_HHMM:
                fmtDate = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                break;
            case FMT_DATE_HHMMSS:
                fmtDate.applyLocalizedPattern("HH:mm:ss");
                break;
        }
        return fmtDate.parse(strDate, pos);
    }

    /**
     * return File Object based on the given file and filepath
     *
     * @param file     current folder file
     * @param filePath file path (relative)
     * @return
     */

    public static File getRealFile(File file, String filePath) {
        File parent = file;
        String path = "";
        String temp = null;
        StringTokenizer token = new StringTokenizer(filePath, "/,\\,//");
        while (token.hasMoreTokens()) {
            temp = token.nextToken();
            if (temp.equals("..")) {
                parent = parent.getParentFile();
                continue;
            }
            if (temp.equals(".")) {
                continue;
            }
            path = path + File.separator + temp;
        }
        File realFile = new File(parent, path);
        return realFile;
    }


    /**
     * filterHTML: 显示页面时,须将如下字符过滤:
     * " => &quot;   , > => &gt;   ,   < => &lt;   '\n'  =>  <br>    ,  '\r' => <br>
     *
     * @param strHTML input html string.
     * @return String 返回格式化后的字符串。
     */
    public static String filterHTML(String strHTML) {
        if (strHTML == null)
            return "";
        StringBuffer sbResult = new StringBuffer();
        int nLen = strHTML.length();
        char chCur;
        for (int i = 0; i < nLen; i++) {
            chCur = strHTML.charAt(i);
            switch (chCur) {
                case '\'':
                    sbResult.append("&apos;");
                    break;
                case '"':
                    sbResult.append("&quot;");
                    break;
                case '>':
                    sbResult.append("&gt;");
                    break;
                case '<':
                    sbResult.append("&lt;");
                    break;
                case '&':
                    sbResult.append("&amp;");
                    break;
                case '\r':
                case '\n':
                    sbResult.append("<br>");
                    break;
                default:
                    sbResult.append(chCur);
                    break;
            }
        }
        return sbResult.toString();
    }

    public static String filterXML(String strXML) {
        if (strXML == null)
            return "";
        StringBuffer sbResult = new StringBuffer();
        int nLen = strXML.length();
        char chCur;
        for (int i = 0; i < nLen; i++) {
            chCur = strXML.charAt(i);
            switch (chCur) {
                case '&':
                    sbResult.append("&amp;");
                    break;
                case '\"':
                    sbResult.append("&quot;");
                    break;
                case '\'':
                    sbResult.append("&apos;");
                    break;
                case '>':
                    sbResult.append("&gt;");
                    break;
                case '<':
                    sbResult.append("&lt;");
                    break;

                case '\n':
                    sbResult.append("<br>");
                    break;
                default:
                    sbResult.append(chCur);
                    break;
            }
        }
        return sbResult.toString();
    }


    /**
     * 用于处理url中的中文参数
     *
     * @param source
     * @return
     */
    public static String chineseProcess(String source) {
        char cBracket1 = '{';
        char cBracket2 = '}';

        //如果为空，或者不含参数
        if (source == null || source.indexOf("{") == -1 || source.indexOf("}") == -1)
            return source;

        char[] cSource = source.toCharArray();
        StringBuffer bufRet = new StringBuffer();


        int beginVariant = -1;
        int endVariant = -1;
        String parameterName = null;

        for (int i = 0; i < cSource.length; i++) {
            if (cBracket1 == cSource[i])   //变量开始
            {
                beginVariant = i;
                continue;
            }

            if (cBracket2 == cSource[i])   //变量结束
            {
                endVariant = i;
            }

            if (beginVariant > -1 && endVariant == -1)   //取变量名
            {
                continue;
            }

            if (beginVariant > -1 && endVariant > -1)   //取得变量的值
            {
                parameterName = source.substring(beginVariant + 1, endVariant);
                bufRet.append(java.net.URLEncoder.encode(parameterName));
                beginVariant = -1;
                endVariant = -1;
                continue;
            }

            bufRet.append(cSource[i]);
        }

        return bufRet.toString();
    }

    public static String toISO(String s)
    {
        try
        {
            if(!isGBK(s))
                return s;
            else
            {
                String s2 = new String(s.getBytes("GBK"),"iso8859-1");
                return s2;
            }
        }catch (Exception e)
        {
            return null;
        }
    }

    /**
    * 判断是否为GBK编码的汉字
    */
    public static boolean isGBK(String str)
    {
        try
        {
            int lengthGBK = str.length();
            int lengthISO = 0;
            String strISO = new String(str.getBytes("ISO8859-1"),"GBK");
            lengthISO = strISO.length();
            if (lengthGBK != lengthISO)
            {
                return false;
            }
        }catch(Exception e)
        {
            return false;
        }
        return true;
  }

}
